<?php

namespace Admin\Controller;

/**
 * 试题控制器
 *
 * @author zhiyuan
 *        
 */
class QuestionsController extends AdminController {
	public function index() {
		$itembank_id = I ( 'itembank' );
		$title = I ( 'title' );
		$questiontype_id = I ( 'get.questiontype' );
		$chapter_id = I ( 'get.chapter' );
		$iteminfo = D ( 'ItemBank' )->field ( 'id,name' )->find ( $itembank_id );
		$map ['itembank'] = array (
				'eq',
				$iteminfo ['id'] 
		);
		// 获取题库中存在的试题类型key
		$questiontype = D ( 'Questions' )->where ( $map )->distinct ( true )->order ( 'questiontype' )->getField ( 'questiontype', true );
		$chapter = D ( 'Questions' )->where ( $map )->distinct ( true )->order ( 'chapter' )->getField ( 'chapter', true );
		if (! empty ( $questiontype_id )) {
			$map ['questiontype'] = array (
					'eq',
					$questiontype_id 
			);
		}
		
		if (! empty ( $chapter_id )) {
			$map ['chapter'] = array (
					'eq',
					$chapter_id 
			);
		}
		
		if (! empty ( $title )) {
			$map ['title'] = array (
					'like',
					'%' . $title . '%' 
			);
		}
		
		$list = $this->lists ( 'Questions', $map, 'questiontype asc,chapter asc,id asc' );
		Cookie ( '__questionsforward__', $_SERVER ['REQUEST_URI'] ); // 记录当前列表页的cookie
		$this->assign ( 'questiontype', $questiontype );
		$this->assign ( 'chapter', $chapter );
		$this->assign ( 'questiontype_id', $questiontype_id );
		$this->assign ( 'chapter_id', $chapter_id );
		$this->assign ( 'list', $list );
		$this->assign ( 'iteminfo', $iteminfo );
		$this->meta_title = '试题信息';
		$this->display ();
	}
	public function add() {
		$itembank_id = I ( 'itembank' );
		$questiontype_id = I ( 'questiontype' , '1' );
		$chapter_id = I ( 'chapter', '1' );
		if (IS_POST) {
			$question = D ( 'Questions' );
			$data = $question->create ();
			if ($data) {
				if ($question->data ( $data )->add ()) {
					$this->success ( '新增成功', Cookie ( '__questionsforward__' ) );
				} else {
					$this->error ( '新增失败' );
				}
			} else {
				$this->error ( $question->getError () );
			}
		}
		$this->assign ( 'questiontype_id', $questiontype_id );
		$this->assign ( 'chapter_id', $chapter_id );
		$this->assign ( 'itembank_id', $itembank_id );
		$this->meta_title = '新增试题';
		$this->display ();
	}
	public function edit($id) {
		if (IS_POST) {
			$question = D ( 'Questions' );
			$data = $question->create ();
			if ($data) {
				if ($question->save ()) {
					$this->success ( '更新成功', Cookie ( '__questionsforward__' ) );
				} else {
					$this->error ( '更新失败' );
				}
			} else {
				$this->error ( $question->getError () );
			}
		} else {
			$questioninfo = D ( 'Questions' )->field ( true )->find ( $id );
			if (false === $questioninfo) {
				$this->error ( '获取题库信息错误' );
			}
			$this->assign ( 'questioninfo', $questioninfo );
			$this->meta_title = '编辑试题';
			$this->display ();
		}
	}
	public function del(){
		
	}
}

?>